﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

using Microsoft.SharePoint;
using Microsoft.Office.Server.UserProfiles;
using Microsoft.Office.DocumentManagement.DocumentSets;

namespace Ko2.Portal.SP_List
{
    public class SPList_PermDocs
    {

        #region Members

        string _siteurl = @"http://localhost/shops/";
        string _listname = @"Первичные документы 2012";

        public enum DocStatus { Черновик = 1, Ожидают_утверждения = 2, Утвержден = 3};

        #endregion

        #region select - CAML text
        public Exception Select(ref DataTable tbl, DateTime parDT)
        {

            Exception ret = null;

            try
            {
                DateTime dt = new DateTime(parDT.Year, parDT.Month, parDT.Day);
                string dtStr = String.Format("{0:0000}-{1:00}-{2:00}", dt.Year, dt.Month, dt.Day);
                DataTable tblTmp = new DataTable("tbl");
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite site = new SPSite(_siteurl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList list = web.Lists[_listname];
                            SPQuery q = new SPQuery();
                            q.ViewAttributes = "Scope=\"Recursive\"";
                            q.Folder = list.RootFolder;
                            q.Query =
@"
    <Where>
        <Eq>
            <FieldRef Name='Created' />
            <Value Type='DateTime'>"
+ String.Format("{0:0000}-{1:00}-{2:00}", dt.Year, dt.Month, dt.Day)
+ @"</Value>
          </Eq>
       </Where>
       <OrderBy>
          <FieldRef Name='Created' Ascending='True' />
       </OrderBy>
    ";
                            SPListItemCollection items = list.GetItems(q);
                            tblTmp = items.GetDataTable();
                        }
                    }
                });
                if (tblTmp != null)
                    tbl = tblTmp;
                else
                    tbl = new DataTable("tbl");
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }

            return ret;
        }
        public Exception SelectGeq(ref DataTable tbl, DateTime parDTStart)
        {

            Exception ret = null;
            try
            {
                DateTime dt = 
                    new DateTime(
                        parDTStart.Year, parDTStart.Month, parDTStart.Day
                        , parDTStart.Hour, parDTStart.Minute, parDTStart.Minute);
                string dtStr = String.Format("{0:0000}-{1:00}-{2:00}T{3:00}:{4:00}:{5:00}"
                    , dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
                DataTable tblTmp = new DataTable("tbl");
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite site = new SPSite(_siteurl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList list = web.Lists[_listname];
                            SPQuery q = new SPQuery();
                            q.ViewAttributes = "Scope=\"Recursive\"";
                            q.Folder = list.RootFolder;
                            q.Query =
@"
    <Where>
        <Geq>
            <FieldRef Name='Modified' />
            <Value Type='DateTime'>"
            + dtStr
            + @"</Value>
          </Geq>
       </Where>
       <OrderBy>
          <FieldRef Name='Modified' Ascending='True' />
       </OrderBy>
    ";
                            SPListItemCollection items = list.GetItems(q);
                            tblTmp = items.GetDataTable();
                        }
                    }
                });
                if (tblTmp != null)
                {
                    tbl = tblTmp;
                    tbl.DefaultView.RowFilter =
String.Format(@" Modified >= '{0}' ", dtStr);
                }
                else
                    tbl = new DataTable("tbl");
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }
        public Exception SelectForApproveList(ref DataTable tbl)
        {

            Exception ret = null;
            try
            {
                DataTable tblTmp = new DataTable("tbl");
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite site = new SPSite(_siteurl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists[_listname];
                            SPQuery q = new SPQuery();
                            q.ViewAttributes = "Scope=\"Recursive\"";
                            q.Folder = lib.RootFolder;
                            // <Query>
                            q.Query =
        @"
<Where>
<Eq>
<FieldRef Name='_x0421__x043e__x0441__x0442__x043e__x044f__x043d__x0438__x0435__x0020__x0443__x0442__x0432__x0435__x0440__x0436__x0434__x0435__x043d__x0438__x044f_' />
<Value Type='Choice'>Ожидают утверждения</Value>
</Eq>
</Where>
"; // </Query>
                            // <ViewFields>
                            q.ViewFields =
    @"
   <FieldRef Name='ID' />
   <FieldRef Name='_x0414__x0430__x0442__x0430__x0020__x043d__x0430__x043a__x043b__x0430__x0434__x043d__x043e__x0439_' />
   <FieldRef Name='_x041d__x043e__x043c__x0435__x0440__x0020__x043d__x0430__x043a__x043b__x0430__x0434__x043d__x043e__x0439_' />
   <FieldRef Name='Shop' />
   <FieldRef Name='Supplier' />
   <FieldRef Name='_x0414__x0430__x0442__x0430__x0020__x043a__x043e__x043c__x043f__x043b__x0435__x043a__x0442__x0430_' />
   <FieldRef Name='Title' />
   <FieldRef Name='_x0421__x043e__x0441__x0442__x043e__x044f__x043d__x0438__x0435__x0020__x0443__x0442__x0432__x0435__x0440__x0436__x0434__x0435__x043d__x0438__x044f_' />
"; // </ViewFields>

                            SPListItemCollection items = lib.GetItems(q);
                            if (items.Count > 0)
                                tblTmp = items.GetDataTable();
                        }
                    }
                });
                if (tblTmp != null)
                {
                    tbl = tblTmp;
                    //tbl.DefaultView.RowFilter = String.Format(@" Modified >= '{0}' ", dtStr);
                }
                else
                    tbl = new DataTable("tbl");
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            return ret;
        }
        #endregion

        #region Approve
        public Exception ApproveOrRegectItem(int parItemID, DocStatus parNewDocStatus)
        {
            Exception ret = null;
            bool bPrev = false;
            bool bPrevWeb = false;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                try
                {
                    using (SPSite site = new SPSite(_siteurl))
                    {
                        bPrev = site.AllowUnsafeUpdates;
                        site.AllowUnsafeUpdates = true;
                        using (SPWeb web = site.OpenWeb())
                        {
                            bPrevWeb = web.AllowUnsafeUpdates;
                            web.AllowUnsafeUpdates = true;
                            //SPDocumentLibrary DocLib = (SPDocumentLibrary)web.Lists[_listname];
                            SPList DocLib = (SPList)web.Lists[_listname];
                            SPListItem item = DocLib.GetItemById(parItemID);
                            if (item == null)
                                throw new Exception("SPList Item Not Found.");

                            if (parNewDocStatus == DocStatus.Черновик)
                                item["Состояние утверждения"] = "Черновик";
                            else if (parNewDocStatus == DocStatus.Ожидают_утверждения)
                                item["Состояние утверждения"] = "Ожидают утверждения";
                            else if (parNewDocStatus == DocStatus.Утвержден)
                                item["Состояние утверждения"] = "Утвержден";

                            //SPModerationStatusType apprtype = SPModerationStatusType.Approved;
                            //item.File.Approve("Утверждено из winForms App");

                            //item.ModerationInformation.Status = SPModerationStatusType.Approved;

                            item.SystemUpdate(false);
                            web.AllowUnsafeUpdates = false;
                        }
                        site.AllowUnsafeUpdates = false;
                    }
                }
                catch (Exception err)
                {
                    ret = new Exception(err.Message, err);
                }
            });

            return ret;
        }
        #endregion

        #region Get
        public Exception GetFilesListByItemId(ref DataTable tbl, int id)
        {
            Exception ret = null;
            DataTable tblTmp = new DataTable("tbl");
            try
            {
                tblTmp.Columns.Add("AuthorName", typeof(String));
                tblTmp.Columns.Add("AuthorID", typeof(int));
                tblTmp.Columns.Add("AuthorLoginName", typeof(String));
                tblTmp.Columns.Add("FileName", typeof(String));
                tblTmp.Columns.Add("url", typeof(String));
                tblTmp.Columns.Add("ServerRelativeUrl", typeof(String));
                tblTmp.Columns.Add("FileTimeCreated", typeof(DateTime));
                tblTmp.Columns.Add("FileTimeLastModified", typeof(DateTime));
                tblTmp.Columns.Add("FileRequiresCheckout", typeof(bool));
                tblTmp.Columns.Add("FileModifiedByID", typeof(int));
                tblTmp.Columns.Add("FileModifiedByLoginName", typeof(String));
                tblTmp.Columns.Add("FileModifiedByName", typeof(String));
                tblTmp.Columns.Add("FileIconUrl", typeof(String));
                tblTmp.Columns.Add("FileCheckInComment", typeof(String));
                tblTmp.Columns.Add("FileLength", typeof(long));
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {

                    using (SPSite site = new SPSite(_siteurl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPDocumentLibrary DocLib = (SPDocumentLibrary)web.Lists[_listname];
                            SPListItem item = DocLib.GetItemById(id);
                            DocumentSet docset = DocumentSet.GetDocumentSet(item.Folder);
                            foreach (SPFile file in docset.Folder.Files)
                            {
                                DataRow newr = tblTmp.NewRow();

                                SPUser author = file.Author;
                                string AuthorName = "";
                                if (author != null)
                                    AuthorName = author.Name;
                                int AuthorID = -1;
                                if (author != null)
                                    AuthorID = author.ID;
                                string AuthorLoginName = "";
                                if (author != null)
                                    AuthorLoginName = author.LoginName;

                                string FileName = file.Name; // = 634653596945151087.jpg
                                string url = file.Url;// = DocLib/ЗП409383/634653596945151087.jpg
                                string ServerRelativeUrl = file.ServerRelativeUrl;// = /shops/DocLib/ЗП409383/634653596945151087.jpg

                                DateTime FileTimeCreated = file.TimeCreated;
                                DateTime FileTimeLastModified = file.TimeLastModified;
                                
                                bool FileRequiresCheckout = file.RequiresCheckout;

                                int FileModifiedByID = -1;
                                string FileModifiedByLoginName = "";
                                string FileModifiedByName = "";
                                if (file.ModifiedBy != null)
                                {
                                    FileModifiedByID = file.ModifiedBy.ID;
                                    FileModifiedByLoginName = file.ModifiedBy.LoginName;
                                    FileModifiedByName = file.ModifiedBy.Name;
                                }

                                string FileIconUrl = file.IconUrl;
                                string FileCheckInComment = file.CheckInComment;
                                
                                long FileLength = file.Length;

                                newr["AuthorName"] = AuthorName;
                                newr["AuthorID"] = AuthorID;
                                newr["AuthorLoginName"] = AuthorLoginName;
                                newr["FileName"] = FileName;
                                newr["url"] = url;
                                newr["ServerRelativeUrl"] = ServerRelativeUrl;
                                newr["FileTimeCreated"] = FileTimeCreated;
                                newr["FileTimeLastModified"] = FileTimeLastModified;
                                newr["FileRequiresCheckout"] = FileRequiresCheckout;
                                newr["FileModifiedByID"] = FileModifiedByID;
                                newr["FileModifiedByLoginName"] = FileModifiedByLoginName;
                                newr["FileModifiedByName"] = FileModifiedByName;
                                newr["FileIconUrl"] = FileIconUrl;
                                newr["FileCheckInComment"] = FileCheckInComment;
                                newr["FileLength"] = FileLength;

                                tblTmp.Rows.Add(newr);

                            }
                        }
                    }
                });
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            if (ret == null)
                tbl = tblTmp;
            return ret;
        }
        public Exception GetFileData(ref byte[] bytes, int parId, string parFileName)
        {
            Exception ret = null;
            byte[] buf = null;
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(_siteurl))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPDocumentLibrary lib = (SPDocumentLibrary)web.Lists[_listname];
                            SPListItem item = lib.GetItemById(parId);
                            DocumentSet docset = DocumentSet.GetDocumentSet(item.Folder);
                            foreach (SPFile file in docset.Folder.Files)
                            {
                                if (file.Name != parFileName)
                                    continue;

                                buf = file.OpenBinary();
                            }
                        }
                    }
                });
            }
            catch (Exception err)
            {
                ret = new Exception(err.Message, err);
            }
            if (buf != null)
                bytes = buf;
            return ret;
        }
        #endregion

    }
}
